package com.qx.cn.tool;

import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionListener implements HttpSessionListener
{
    private static Map hUserName = new ConcurrentHashMap();
    
    @Override
    public void sessionCreated(HttpSessionEvent se)
    {
    }
    
    @Override
    public void sessionDestroyed(HttpSessionEvent se)
    {
        hUserName.remove(se.getSession().getId());
    }
    
    public static boolean isAlreadyEnter(HttpSession session, Long sUserName)
    {
        boolean flag = false;
        if (hUserName.containsValue(sUserName))
        {
            flag = true;
            Iterator iter = hUserName.entrySet().iterator();
            while (iter.hasNext())
            {
                Map.Entry entry = (Map.Entry)iter.next();
                Object key = entry.getKey();
                Object val = entry.getValue();
                if (Long.valueOf(sUserName.longValue()).equals(val))
                {
                    hUserName.remove(key);
                }
            }
            hUserName.put(session.getId(), sUserName);
        }
        else
        {
            flag = false;
            hUserName.put(session.getId(), sUserName);
        }
        
        return flag;
    }
    
    public static boolean isOnline(HttpSession session)
    {
        return hUserName.containsKey(session.getId());
    }
}